#include "writer.h"
#include <iostream>
Writer::Writer(Library * lib, int writeTime): lib(lib), writeTime(writeTime), stopWriting(false)
{
    lib->registerPerson();
}

void Writer::run()
{
    while(true) {
        if(lib->isClosed()) return;

        if (!stopWriting && (booksWritten.empty() || random() % 5 == 0)) {
            int book = lib->addBook();
            if (book == -1) {
                stopWriting = true;
            } else {
                booksWritten.append(book);
            }
            usleep(writeTime);
        } else {
            if(booksWritten.empty()) return; //lib full, no books written

            int index = booksWritten[random() % booksWritten.size()];
            lib->acquireBook(index);
            usleep(writeTime);
            lib->releaseBook(index);
        }
    }
}
